﻿using AntdUI;
using DataTurnClient.Control;
using DataTurnClient.Controls;
using DataTurnClient.Interface;
using DataTurnClient.Server;
using DataTurnClient.ViewModel;
using MetroFramework.Controls;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataTurnClient
{
    public partial class MainView : AntdUI.Window, IViewFor<MainTurnViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (MainTurnViewModel)value;
        }

        public MainTurnViewModel ViewModel { get; set; }

        public MainView()
        {
            InitializeComponent();

            InitLoad();

            InitBindings();

            InitColumns();

            InitEvent();
        }

        public Job CurrentJobRows { get => table_base.SelectedIndex < 1 ? new Job() : ViewModel.JobList[table_base.SelectedIndex - 1]; }

        private void InitLoad()
        {
            Globals.DbType = (SqlSugar.DbType)Convert.ToInt32(ConfigurationManager.AppSettings["DbType"]);
            Globals.DbConnect = ConfigurationManager.AppSettings["DbConnect"];

            System.Timers.Timer t1 = new System.Timers.Timer(1000);
            t1.Elapsed += new System.Timers.ElapsedEventHandler(AllRunTime);
            t1.AutoReset = true;
            t1.Enabled = true;

        }

        private void InitColumns()
        {
            table_base.Columns = new AntdUI.ColumnCollection()
            { 
                new AntdUI.Column("JobCode","任务编码"),
                new AntdUI.Column("JobName","任务名称"),
                new AntdUI.Column("JobStatus","状态"),
                new AntdUI.Column("JobRunTime","执行时间"),
                new AntdUI.Column("JobWeek","执行星期"),
                new AntdUI.Column("JobDetail","任务描述"),
                new AntdUI.Column("JobRunStatus","运行状态"),
                new AntdUI.Column("JobRoute","任务路由"),
                new AntdUI.Column("JobMode","请求模式"),
                new Column("CellLinks", "操作",ColumnAlign.Center){ Fixed = true },
            };
            table_base.Binding(ViewModel.JobList);

            table_log.Columns = new ColumnCollection()
            {
                new AntdUI.Column("HappenTime","发生时间"),
                new AntdUI.Column("HappenModel","发生模块"),
                new AntdUI.Column("HappenDtal","描述"),
                new Column("CellLinks", "操作",ColumnAlign.Center){ Fixed = true },
            };
            table_log.Binding(ViewModel.LogList);
        }

        private void InitBindings()
        {
            Locator.CurrentMutable.RegisterLazySingleton<IDBHelperService>(() => new DBHelperService());
            Locator.CurrentMutable.RegisterLazySingleton<IAntdMessage>(() => new AntdMessage());
            Locator.CurrentMutable.RegisterLazySingleton<ITool>(() => new Tool());
            Locator.CurrentMutable.RegisterLazySingleton(() => new TimeService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new LogService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new MainTurn());
            ViewModel = new MainTurnViewModel(RxApp.MainThreadScheduler);
            this.WhenActivated(d =>
            {

                table_base.Events().DoubleClick.Do(x =>
                {
                    IndexAction(0, null);
                }).Subscribe().DisposeWith(d);

                table_base.Events().MouseClick.Do(x =>
                {
                    if (x.Button == MouseButtons.Right)
                    {
                        var ant = Locator.Current.GetService<IAntdMessage>();
                        var config = ant.ConTextMenuConfig(table_base, it =>
                        {
                            int i = Globals.ContextMenuItems.FindIndex(p => p.Text == it.Text);
                            IndexAction(i, it);
                        });
                        AntdUI.ContextMenuStrip.open(config);
                    }
                }).Subscribe().DisposeWith(d);

                this.button_manageLine.Events().Click.Do(x =>
                {
                    RouteView job = new RouteView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                this.button_set.Events().Click.Do(x =>
                {
                    SetView job = new SetView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                this.button_time.Events().Click.Do(x =>
                {
                    TimerView job = new TimerView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                // 任务数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.JobList,
                    v => v.table_base.DataSource)
                    .DisposeWith(d);

                ViewModel.WhenAnyValue(vm => vm.IsTimer).Subscribe(x =>
                {
                    checkbox_isTime.Checked = x;
                });

            });
        }

        private void InitEvent()
        {
            //初始化
            ViewModel.ReloadTableCommand.Execute().Subscribe(result =>
            {
                if (!result.Success)
                {
                    var config = new AntdUI.Notification.Config(this,"提醒",$"初始化出错：{result.Message}", TType.Error, TAlignFrom.BR);
                    AntdUI.Notification.open(config);
                }
            });
            ViewModel.SelectJobCommand.Execute().Subscribe();
            ViewModel.SelectSetCommand.Execute().Subscribe();
            CheckForIllegalCrossThreadCalls = false;

            table_base.CellButtonClick += async (s, e) =>
            {
                var buttontext = e.Btn.Text;
                if (e.Record is Job job)
                {
                    int runCode = 0;
                    switch (buttontext)
                    {
                        case "编辑":
                            runCode = 2;
                            break;
                        case "删除":
                            runCode = 3;
                            break;
                        case "更改状态":
                            runCode = 4;
                            break;
                        case "执行":
                            runCode = 5; 
                            break;
                    }
                    IndexAction(runCode, null);
                }
            };

            table_log.CellButtonClick += (s, e) =>
            {
                var buttontext = e.Btn.Text;
                if (e.Record is Log log)
                {
                    switch (buttontext)
                    {
                        case "查看":
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine($"{log.HappenModel} {log.HappenTime}");
                            sb.AppendLine($"{log.HappenDtal}");
                            var configSelect = new AntdUI.Modal.Config(this, "提醒", sb, TType.Success);
                            AntdUI.Modal.open(configSelect);
                            break;
                        case "删除":
                            var config = new AntdUI.Modal.Config(this, "提醒", $"是否删除当前选择的记录 ?", TType.Error);
                            var dialog = AntdUI.Modal.open(config);
                            if (dialog == DialogResult.OK)
                            {
                                ViewModel.DeleteLogCommand.Execute(log).Subscribe();
                            }
                            break;
                    }
                }
            };

            checkbox_isTime.CheckedChanged += (s, e) =>
            {
                ViewModel.IsTimer = e.Value;
            };

        }

        /// <summary>
        /// 抽屉方法，根据索引打开业务
        /// </summary>
        /// <param name="i"></param>
        /// <param name="it"></param>
        private void IndexAction(int i, ContextMenuStripItem it)
        {
            var message = Locator.Current.GetService<IAntdMessage>();
            switch (i)
            {
                case 0:
                    JobView selectJob = new JobView(Enum.DType.ControlType.Select);
                    selectJob.ViewModel.Job = CurrentJobRows;
                    var selectConfig = message.DrawerConfig(this, selectJob);
                    selectConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(selectConfig);
                    break;
                case 1:
                    JobView addJob = new JobView(Enum.DType.ControlType.Add);
                    addJob.ViewModel.Job = new Job();
                    var addConfig = message.DrawerConfig(this, addJob);
                    addConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(addConfig);
                    break;
                case 2:
                    JobView editJob = new JobView(Enum.DType.ControlType.Edit);
                    editJob.ViewModel.Job = CurrentJobRows;
                    var editConfig = message.DrawerConfig(this, editJob);
                    editConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(editConfig);
                    break;
                case 3:
                    if (table_base.SelectedIndex > 0 )
                    {
                        var config = new AntdUI.Modal.Config(this, "提醒", $"是否删除当前选择的记录 ?", TType.Error);
                        var dialog = AntdUI.Modal.open(config);
                        if (dialog == DialogResult.OK)
                        {
                            ViewModel.DeleteJobCommand.Execute(CurrentJobRows).Subscribe(result =>
                            {
                                if (!result.Success)
                                {
                                    var configDelete = new AntdUI.Notification.Config(this, "提醒", "未删除", TType.Error, TAlignFrom.Top);
                                    AntdUI.Notification.open(configDelete);
                                }
                            });
                        }
                    }
                    break;
                case 4:
                    if (table_base.SelectedIndex > 0)
                    {
                        var config = new AntdUI.Modal.Config(this, "提醒", $"是否更改当前选择记录的启用标识 ?", TType.Info);
                        var dialog = AntdUI.Modal.open(config);
                        if (dialog == DialogResult.OK)
                        {
                            ViewModel.ChangeJobStatusCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                        }
                    }
                    break;
                case 5:
                    if (!string.IsNullOrEmpty(CurrentJobRows.JobCode))
                    {
                        ViewModel.RunJobCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                    }
                    break;
                case 6:
                    ViewModel.SelectJobCommand.Execute().Subscribe();
                    break;
                case 7:
                    ViewModel.RunAllJobCommand.Execute().Subscribe();
                    break;
                default:
                    Console.WriteLine($"点击：{it.Text}");
                    break;
            }
        }

        /// <summary>
        /// 根据控件打开抽屉
        /// </summary>
        /// <param name="Control"></param>
        private void OpenDrowing(System.Windows.Forms.Control Control)
        {
            var message = Locator.Current.GetService<IAntdMessage>();

            var config = message.DrawerConfig(this, Control);
            config.OnClose = () =>
            {
                ViewModel.SelectJobCommand.Execute().Subscribe();
                ViewModel.SelectSetCommand.Execute().Subscribe();
            };
            AntdUI.Drawer.open(config);
        }

        private void AllRunTime(object sender, EventArgs e)
        {
            ViewModel.IsRunTimeCommand.Execute().Subscribe();
        }

    }
}
